package com.intpro.demo.Controller;

import com.intpro.demo.DAO.CommonRep;
import com.intpro.demo.Service.VeryService;
import com.intpro.demo.Utils.CodeException;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin
@RestController
@RequestMapping("api/very")
public class VeryController
{

	@Autowired
	private VeryService veryService;

	@RequestMapping(value = "send", method = RequestMethod.POST)
	public CommonRep send(@RequestBody Map<String, String> req) throws CodeException
	{
		var phone = req.get("phone");
		if (phone == null)
		{
			throw CodeException.NotNullErr();
		}
		var v = veryService.findPhone(phone);

		if (v != null && v.checked)
		{
			throw CodeException.PhoneRepeatErr();
		}
		try
		{
			veryService.createVeryCode(phone);
		} catch (Exception e)
		{
			throw CodeException.CodeCreateErr();
		}
		return new CommonRep();
	}


	@RequestMapping(value = "check", method = RequestMethod.POST)
	public CommonRep check(@RequestBody Map<String, String> req) throws CodeException
	{
		var phone = req.get("phone");
		var code = req.get("code");
		if (!veryService.checkCode(phone, code))
		{
			throw CodeException.CodeCheckErr();
		}
		return new CommonRep();
	}

}